#!/usr/bin/env python3
import asyncio
import websockets
import logging
import json
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

async def handler(websocket, path):
    """WebSocket处理器 - 兼容最新版本"""
    client_address = websocket.remote_address
    logger.info(f"新客户端连接: {client_address}")
    
    try:
        async for message in websocket:
            logger.info(f"收到消息: {message}")
            
            # 尝试解析JSON
            try:
                data = json.loads(message)
                message_type = data.get('type')
                
                if message_type == 'AUTH':
                    response = {
                        'type': 'AUTH_RESPONSE',
                        'data': {
                            'status': 'success',
                            'timestamp': datetime.now().isoformat()
                        }
                    }
                    await websocket.send(json.dumps(response))
                    logger.info("认证响应发送成功")
                    
                elif message_type == 'HEARTBEAT':
                    response = {
                        'type': 'HEARTBEAT_RESPONSE',
                        'data': {
                            'timestamp': datetime.now().isoformat()
                        }
                    }
                    await websocket.send(json.dumps(response))
                    logger.info("心跳响应发送成功")
                    
                elif message_type == 'PATIENT_REPORT':
                    response = {
                        'type': 'PATIENT_REPORT_RESPONSE',
                        'data': {
                            'status': 'success',
                            'timestamp': datetime.now().isoformat()
                        }
                    }
                    await websocket.send(json.dumps(response))
                    logger.info("患者上报响应发送成功")
                    
                elif message_type == 'USER_REGISTER':
                    response = {
                        'type': 'USER_REGISTER_RESPONSE',
                        'data': {
                            'status': 'success',
                            'timestamp': datetime.now().isoformat()
                        }
                    }
                    await websocket.send(json.dumps(response))
                    logger.info("用户注册响应发送成功")
                    
                else:
                    # 简单回显
                    response = f"服务器收到: {message}"
                    await websocket.send(response)
                    logger.info(f"发送回显: {response}")
                    
            except json.JSONDecodeError:
                # 如果不是JSON，简单回显
                response = f"服务器收到: {message}"
                await websocket.send(response)
                logger.info(f"发送回显: {response}")
                
    except websockets.exceptions.ConnectionClosed:
        logger.info(f"客户端断开连接: {client_address}")
    except Exception as e:
        logger.error(f"处理连接时出错: {e}")
    finally:
        logger.info(f"连接结束: {client_address}")

async def main():
    host = "0.0.0.0"
    port = 8080
    logger.info(f"启动WebSocket服务器: ws://{host}:{port}")
    
    try:
        # 使用最新版本的websockets库
        async with websockets.serve(handler, host, port):
            logger.info("WebSocket服务器启动成功")
            await asyncio.Future()
            
    except Exception as e:
        logger.error(f"服务器启动失败: {e}")

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        logger.info("服务器停止")
    except Exception as e:
        logger.error(f"服务器运行出错: {e}") 